package nju.bishe.weibo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weibo4android.WeiboException;
import weibo4android.org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import nju.bishe.weibo.data.Address;
import nju.bishe.weibo.data.Position;
import nju.bishe.weibo.data.UserToken;
import nju.bishe.weibo.task.GenericTask;
import nju.bishe.weibo.task.TaskAdapter;
import nju.bishe.weibo.task.TaskListener;
import nju.bishe.weibo.task.TaskParams;
import nju.bishe.weibo.task.TaskResult;
import nju.bishe.weibo.ui.base.WithHeaderActivity;
import nju.bishe.weibo.util.WeiboLocationManager;

public class DrinkerySuggestActivity extends WithHeaderActivity{
	private static final String TAG = "DrinkerySuggestActivity";
	private static final String LAUNCH_ACTION = "nju.bishe.weibo.DrinkeryActivity";
	private static final String GPsTAG = "GPSTestActivity";
	private LocationManager locationManager;
	private boolean status = false;
	private static Location currentLocation = null;
	private ListView drinkery_list;
	private static final String POSITION_ID = "positionId";
	private List<Position> positions;
	private Address currentAddress;
	private GenericTask mSignInTask;
	private ArrayAdapter<String> adapter;
	private LinearLayout ll_current;
	private TextView current_msg;
	private TextView current_short;
	private TextView current_addr;
	private SimpleAdapter  simpleAdapter;
	private Position currentPosition = null;
	private WeiboLocationManager weiboLocationManager = new WeiboLocationManager();
	List<Map<String,String>> addr_map=new ArrayList<Map<String,String>>(); 
	private String[] from = {"name","addr","navi"};
	  
	private TaskListener mDrinkeryListener = new TaskAdapter() {
		
		@Override
		public void onPreExecute(GenericTask task) {
			// TODO Auto-generated method stub
			current_short=(TextView)findViewById(R.id.drinkery_current_shortname);
			current_short.setText("获取位置信息中...");
			animRotate(refreshButton);
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			try {
				currentAddress = TwitterApplication.mApi.geoToPosition(
						currentLocation.getLatitude(), currentLocation
								.getLongitude());
				refreshButton.clearAnimation();
			} catch (WeiboException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			

			// 将Location转为Position
			if (currentLocation != null) {
				currentPosition = Position
						.constructFromLocation(currentLocation);
			}
			
			//显示当前位置
            current_msg=(TextView)findViewById(R.id.drinkery_current_msg);
        	current_short=(TextView)findViewById(R.id.drinkery_current_shortname);
        	current_addr=(TextView)findViewById(R.id.drinkery_current_full);
        	ll_current = (LinearLayout)findViewById(R.id.drinkery_current_layout);
        	
        	
            if(null==currentAddress){                	
            	current_msg.setText("糟糕~~由于被Google拒绝，没法详细定位当前位置，可尝试重新加载");
            	current_short.setVisibility(View.GONE);
            	current_addr.setVisibility(View.GONE);
            }
            else{

            	current_short.setText(currentAddress.getWholeName());
            	//current_short.setText(currentPosition.getName());
            	//current_addr.setText(currentPosition.getAddress());
                ll_current.setOnClickListener(new View.OnClickListener() {
                	  public void onClick(View v) {
                	  // TODO Auto-generated method stub
                		  Intent intent = new Intent(DrinkerySuggestActivity.this,DrinkeryActivity.class);
                          Bundle bundle = new Bundle();
                          bundle.putParcelable(POSITION_ID, currentPosition);
                          intent.putExtras(bundle);
                          startActivity(intent);
                	  }
                	  });
            }
			try {
				positions = weiboLocationManager.getDrinkeryLocations(Double.parseDouble(currentPosition.getLongitude()), Double.parseDouble(currentPosition.getLatitude()));
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

              
              int[] to = {R.id.drinkery_position_shortname,R.id.drinkery_position_addr,R.id.drinkery_position_nav};
              //b2.show();
              for(int i =0; i<positions.size();i++){
              	Map<String,String> item=new HashMap<String,String>();
					item.put(from[0], positions.get(i).getName());
					item.put(from[1], positions.get(i).getAddress());
					item.put(from[2], positions.get(i).getNavigator());					
					addr_map.add(item);
              }
              
			// 获得周围的positions
			WeiboLocationManager locationManager = new WeiboLocationManager();
			try {
				positions = locationManager.getNearByPostions(currentPosition);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			drinkery_list = (ListView) findViewById(R.id.drinkery_list);
			
            simpleAdapter=new SimpleAdapter(DrinkerySuggestActivity.this,addr_map,R.layout.drinkery_item,from,to); 
			drinkery_list.setAdapter(simpleAdapter);


			// set lisenter
			drinkery_list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long id) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(DrinkerySuggestActivity.this,
							DrinkeryActivity.class);
					Bundle bundle = new Bundle();
					bundle.putParcelable(POSITION_ID, positions.get(position));
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			
			  
              
              searchButton.setOnClickListener(new View.OnClickListener() {
					
					public void onClick(View v) {
						// TODO Auto-generated method stub
						
						try {
							//positions = weiboLocationManager.getSearchedPostion(search_key.getText().toString());
							positions = weiboLocationManager.getDrinkeryLocations(currentLocation
									.getLongitude(), currentLocation.getLatitude());

							addr_map.clear();
				            for(int i =0; i<positions.size();i++){
				            	Map<String,String> item=new HashMap<String,String>();
								item.put(from[0], positions.get(i).getName());
								item.put(from[1], positions.get(i).getAddress());
								item.put(from[2], positions.get(i).getNavigator());	
								addr_map.add(item);
				            }
				              
							if(addr_map.size()==0){
								ll_current.setVisibility(View.VISIBLE);
								current_msg.setText("无搜索结果");
		                    	current_short.setVisibility(View.GONE);
		                    	current_addr.setVisibility(View.GONE);
		                    	//sign_list.invalidate();  
								simpleAdapter.notifyDataSetChanged();
							}
							else{
								ll_current.setVisibility(View.GONE);
								simpleAdapter.notifyDataSetChanged();

		                    	//sign_list.invalidate();  
							}
						} catch (WeiboException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
		}

		@Override
		public String getName() {
			return "SignInTask";
		}
	};

	protected boolean _onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate()...");
		
		if(super._onCreate(savedInstanceState)){
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			requestWindowFeature(Window.FEATURE_PROGRESS);
		
			setContentView(R.layout.drinkery);
			initHeader(HEADER_STYLE_HOME);
			setHeaderTitle("酒店查询");

		mSignInTask = new DrinkeryTask();
		mSignInTask.setListener(mDrinkeryListener);
		mSignInTask.execute();
		}
		return true;

	}

	private void setHeaderTitle() {
		// TODO Auto-generated method stub
		TextView title = (TextView) findViewById(R.id.title);
		//title.setBackgroundDrawable( new BitmapDrawable());
		title.setBackgroundResource(android.R.color.transparent);

		LayoutParams lp = new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		lp.setMargins(3, 12, 0, 0);
		title.setLayoutParams(lp);
		// 中文粗体
		TextPaint tp = title.getPaint();
		tp.setFakeBoldText(true);
	}

	private class DrinkeryTask extends GenericTask {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			String serviceName = Context.LOCATION_SERVICE;
			LocationManager locationManager = (LocationManager) getSystemService(serviceName);
			// String provider = LocationManager.GPS_PROVIDER;
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			String provider = locationManager.getBestProvider(criteria, true);
			long preTime = System.currentTimeMillis();
			long afterTime;
			while (currentLocation == null) {
				currentLocation = locationManager
						.getLastKnownLocation(provider);
				afterTime = System.currentTimeMillis();
				if ((afterTime - preTime) > 5000) // 超过5s
				{
					break;
				}
			}
			
			//get from huancun
			WeiboLocationManager weiboLocationManager = new WeiboLocationManager();
			Position position = weiboLocationManager.getPosition();
			currentLocation = new Location(provider);
			currentLocation.setLatitude(Double.parseDouble(position.getLatitude()));
			currentLocation.setLongitude(Double.parseDouble(position.getLongitude()));

			if (currentLocation != null) {
				return TaskResult.OK;
			} else {
				return TaskResult.FAILED;
			}
		}
	}
}
/*
 class DrinkeryAdapter extends BaseAdapter{    
	 private final Context context;
     private final List<Map<String,String>> reviews;
	 private  ViewHolder vh=new ViewHolder();
	 
	 DrinkeryAdapter(Context context, List<Map<String,String>> reviews){
		 this.context = context;
	     this.reviews = reviews;
	 }
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.reviews.size();
	}
	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return this.reviews.get(position);
	}
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Map<String,String> current=this.reviews.get(position);		

		View drinkery_item = LayoutInflater.from(context).inflate(R.layout.drinkery_item,null);
		vh.drinkery_short=(TextView)drinkery_item.findViewById(R.id.drinkery_position_shortname);
		vh.drinkery_addr=(TextView)drinkery_item.findViewById(R.id.drinkery_position_addr);
		vh.drinkery_rating=(RatingBar)drinkery_item.findViewById(R.id.drinkery_position_rating);

        String[] from = {"name","addr","tel","navi"};
		vh.drinkery_short.setText(current.get(from[0]));
		vh.drinkery_addr.setText(current.get(from[1]));
		vh.drinkery_tel.setText(current.get(from[2]));
		vh.drinkery_rating.setNumStars(Integer.parseInt(current.get(from[3])));
		return drinkery_item;
	}

	private static class ViewHolder{
		TextView drinkery_short;//昵称
		TextView drinkery_full;//时间
		TextView drinkery_addr;//时间
		TextView drinkery_tel;//时间
		RatingBar drinkery_rating;
	}
 }
*/